package Code;

import java.util.List;

public class Code160 {
     static class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val= x;
            next = null;
        }

    }
    static ListNode getIntersectionNode(ListNode headA, ListNode headB){
        if(headA == null || headB == null){
            return null;
        }
        ListNode pA = headA, pB = headB;
        while(pA != pB){
            pA = pA== null? headB : pA.next;
            pB = pB== null? headA : pB.next;

        }
        return pA;
    }
    public static void main(String[] args) {
        ListNode commonNode = new ListNode(8);
        ListNode headA = new ListNode(4);
        headA.next = new ListNode(1);
        headA.next.next = commonNode;
        commonNode.next = new ListNode(4);
        commonNode.next.next = new ListNode(5);

        ListNode headB = new ListNode(5);
        headB.next = new ListNode(6);
        headB.next.next = new ListNode(1);
        headB.next.next.next = commonNode;

          ListNode intersectionNode = getIntersectionNode(headA, headB);
        if (intersectionNode != null) {
            System.out.println("相交节点的值为: " + intersectionNode.val);
        } else {
            System.out.println("两个链表不相交");
        }
    }
}
